import axios from 'axios';
import qs from 'qs';
import {reactive, ref} from 'vue';
import { useRouter } from 'vue-router';

const instance = axios.create({
    baseURL: 'http://123.60.129.240', // 设置请求的基础URL
    timeout: 10000, // 设置请求超时时间
});

const router = useRouter();

instance.interceptors.request.use((config) => {
    const userString = ref(getUser());
    // console.log(userString.value);
    config.headers.Authorization = userString.value.token;
    return config;
});

const tokenAxios = {
    async get(url, params) {
        try {
            const response = await instance.get(url, { params });
            return response.data;
        } catch (error) {
            handleRequestError(error);
            throw error;
        }
    },
    async post(url, params) {
        try {
            const response = await instance.post(url, qs.stringify(params));
            return response.data;
        } catch (error) {
            handleRequestError(error);
            throw error;
        }
    },
};

function handleRequestError(error) {
    if (error.response && error.response.status === 401) {
        // 处理未授权的请求，例如跳转到登录页
        router.push('/');
    } else {
        console.error(error);
    }
}

export const useTokenAxios = () => {
    return reactive(tokenAxios);
};

export default tokenAxios;
